import wepy from 'wepy'
import config from '../config'
// request
import { request } from './request.utils'
// track
import { TrackObj } from '../track/index'
// tips
import Tips from './tips.utils'

const getAppInfo = function({ instance = null } = {}) {
  if (instance == null) return
  return !!instance.$isComponent ? instance.$root.$parent : instance.$parent
}

const getGlobalData = function({ instance = {} } = {}) {
  return wepy.$instance.globalData || getAppInfo({ instance }).globalData
}

// 函数节流防止快速点击页面重复跳转
let lastTime = 0
const throttleFunc = (fn, delay = 0) => {
  return () => {
    let now = +new Date()
    if (now - lastTime > delay) {
      lastTime = now
      fn.apply()
    }
  }
}

const navigateTo = function({
  url = '',
  success = null,
  fail = null,
  complete = null
} = {}) {
  wx.navigateTo({
    url,
    success,
    fail,
    complete
  })
}

const redirectTo = function({
  url = '',
  success = null,
  fail = null,
  complete = null
} = {}) {
  wx.redirectTo({
    url,
    success,
    fail,
    complete
  })
}

const reLaunch = function({
  url = '',
  success = null,
  fail = null,
  complete = null
} = {}) {
  wx.reLaunch({
    url,
    success,
    fail,
    complete
  })
}

const switchTab = function({
  url = '',
  success = null,
  fail = null,
  complete = null
} = {}) {
  wx.switchTab({
    url,
    success,
    fail,
    complete
  })
}

const navigateBack = function({ delta = 1 } = {}) {
  wx.navigateBack({
    delta
  })
}

wx.$getAppInfo = getAppInfo
wx.$getGlobalData = getGlobalData
wx.$env = config['ENV']
wx.$request = request
// track
TrackObj.setEnv(config['ENV'])
wx.$track = TrackObj
//tips
wx.$tips = Tips
// router
wx.$navigateTo = navigateTo
wx.$redirectTo = redirectTo
wx.$reLaunch = reLaunch
wx.$switchTab = switchTab
wx.$navigateBack = navigateBack
wx.$throttleFunc = throttleFunc
